# students/router.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from ..database import get_db
from . import schemas, crud

router = APIRouter(prefix="/students", tags=["students"])

@router.post("/", response_model=schemas.Student, summary="添加学生", description="创建新的学生记录")
def create_student(student: schemas.StudentCreate, db: Session = Depends(get_db)):
    db_student = crud.crud_student.get_by_id(db, student.student_id)
    if db_student:
        raise HTTPException(status_code=400, detail="Student already exists")
    return crud.crud_student.create(db, student)

@router.get("/", response_model=List[schemas.Student], summary="获取所有学生", description="获取所有学生记录，支持分页")
def read_students(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
    return crud.crud_student.get_all(db, skip=skip, limit=limit)

@router.get("/filter/", response_model=List[schemas.Student], summary="筛选学生", description="根据学生ID、姓名或班级筛选学生记录")
def filter_students(
    student_id: Optional[str] = None,
    name: Optional[str] = None,
    class_name: Optional[str] = None,
    db: Session = Depends(get_db)
):
    return crud.crud_student.get_by_filter(db, student_id, name, class_name)

@router.get("/{student_id}", response_model=schemas.Student, summary="获取单个学生", description="根据学生ID获取学生详情")
def read_student(student_id: str, db: Session = Depends(get_db)):
    db_student = crud.crud_student.get_by_id(db, student_id)
    if db_student is None:
        raise HTTPException(status_code=404, detail="Student not found")
    return db_student

@router.put("/{student_id}", response_model=schemas.Student, summary="更新学生信息", description="根据学生ID更新学生记录")
def update_student(student_id: str, student: schemas.StudentUpdate, db: Session = Depends(get_db)):
    db_student = crud.crud_student.update(db, student_id, student)
    if db_student is None:
        raise HTTPException(status_code=404, detail="Student not found")
    return db_student

@router.delete("/{student_id}", summary="删除学生", description="根据学生ID删除学生记录")
def delete_student(student_id: str, db: Session = Depends(get_db)):
    success = crud.crud_student.delete(db, student_id)
    if not success:
        raise HTTPException(status_code=404, detail="Student not found")
    return {"message": "Student deleted successfully"}